import React, { useState, useEffect } from "react";
import { Route, Redirect } from "react-router-dom";
import { useCustomState } from '@/hooks/useEffect';
import { connect } from 'react-redux'
import Cookies from 'js-cookie'
import {
    hasPermission,
    permissionCodes as pCodes
} from '@/routes/permission'
import { message } from 'antd'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css';
import { isLowerIEVersion } from '@/utils'
import { storage } from '@/utils/storage'
import config from '@/config'
import {
    ADD_TABS,
    REMOVE_TABS,
    CHANGE_TABS,
    FILTER_TABS,
} from '@/store/actionTypes'

nprogress.configure({ easing: 'ease', speed: 500, showSpinner: false });
const FrontendAuth = (props) => {
    const { routerConfig, location } = props;
    const { pathname } = location;
    useCustomState(nprogress.start());
    useEffect(() => {
        nprogress.done();
        // return () => nprogress.start();
    });
    const setTitle = (title) => {
        const currentPath = window.location.pathname
        document.title = config.setting.title + '-' + routerConfig.meta.title
        if (routerConfig.routes && routerConfig.routes.length) {
            routerConfig.routes.map(el => {
                if (el.path === currentPath) {
                    document.title = config.setting.title + '-' + el.meta.title
                }
            })
        }
    }
    const render = () => {
        const isLogin = Cookies.get('token')
        // 如果该路由不用进行权限校验，登录状态下登陆页除外
        // 因为登陆后，无法跳转到登陆页
        // 这部分代码，是为了在非登陆状态下，访问不需要权限校验的路由
        const targetRouterConfig = routerConfig
        // 判断ie < 11直接跳转下载推荐浏览器
        // console.log(props, 'props');
        let lowerBrowser = isLowerIEVersion() && isLowerIEVersion() < 11
        if (lowerBrowser && pathname !== '/browser') {
            return <Redirect to="/browser" />;
        }
        // 设置网站 title
        setTitle()
        if (isLogin) {
            // 如果是登陆状态，想要跳转到登陆，重定向到主页
            if (pathname === "/login") {
                return <Redirect to="/" />;
            } else {
                // 如果路由合法，就跳转到相应的路由
                // console.log(targetRouterConfig.meta.roles, 'targetRouterConfig.meta.roles');
                // hasPermission([targetRouterConfig.meta.roles])
                if (targetRouterConfig) {
                    return <Route exact={targetRouterConfig.exact} path={pathname} render={(pProps) => {
                        return <targetRouterConfig.component {...props} {...pProps} routes={targetRouterConfig.routes}></targetRouterConfig.component>
                    }}></Route>
                } else {
                    // 如果路由不合法，重定向到 404 页面
                    return <Redirect to="/404" />;
                }
            }
        } else {
            // 非登陆状态下，当路由合法时且需要权限校验时，跳转到登陆页面，要求登陆
            if (!targetRouterConfig) {
                // 非登陆状态下，路由不合法时，重定向至 404
                return <Redirect to="/404" />;
            }
            if (targetRouterConfig && !targetRouterConfig.auth) {
                return <Route exact={targetRouterConfig.exact} path={pathname} render={(pProps) => {
                    return <targetRouterConfig.component {...props} {...pProps} routes={targetRouterConfig.routes}></targetRouterConfig.component>
                }}></Route>
            } else if (targetRouterConfig && targetRouterConfig.auth) {
                console.log('未登录，跳转登录')
                // message.error('登录信息失效，请重新登录！')
                storage.remove('userInfo')
                props.setUserInfo({})
                return <Redirect to="/login" />;
            } else {
                // 非登陆状态下，路由不合法时，重定向至 404
                return <Redirect to="/404" />;
            }
        }
    }
    return render()
}

function arePropsEqual (prevProps, nextProps) {
    const prevPath = prevProps.location.pathname
    const nextPath = nextProps.location.pathname
    const prevScroll = prevProps.scroll || {}
    const nextprevScroll = nextProps.scroll || {}
    nprogress.done();
    // console.log(nextPath, 'nextPath');
    if (prevPath === nextPath) {
        if (prevScroll.y !== nextprevScroll.y) {
            return false
        }
        return true
    }
    let _prev = JSON.stringify(prevProps)
    let _next = JSON.stringify(nextProps)
    return _prev === _next
    // return false
}
//需要触发什么行为
function mapDispatchToProps (dispatch, props) {
    return {
        onLogoClick: (activeKey) => {
            dispatch({
                type: CHANGE_TABS,
                ...props,
                activeKey
            })
        },
        setTheme: (val) => dispatch({
            type: 'setTheme',
            value: {
                ...val
            }
        }),
        addTabs: async (val) => {
            await dispatch({
                type: ADD_TABS,
                ...props,
                ...val
            })
        },
        removeTabs: (activeKey, isCloseOpen) => dispatch({
            type: REMOVE_TABS,
            activeKey,
            isCloseOpen,
            ...props
        }),
        changeTabs: (val) => {
            if (props.location.pathname === val.activeKey) return
            dispatch({
                type: CHANGE_TABS,
                ...props,
                ...val
            })
        },
        filterTabs: (val) => dispatch({
            type: FILTER_TABS,
            value: val,
            ...props
        }),
        logout: (value) => {
            dispatch({
                type: 'logout',
                value,
                ...props
            })
        },
        setUserInfo: (value) => {
            dispatch({
                type: 'setUserInfo',
                value,
                ...props
            })
        },
    }
}
// React.memo 可接受2个参数，第一个参数为纯函数的组件，第二个参数用于对比props控制是否刷新
// 类似 shouldComponentUpdate()，与 shouldComponentUpdate 不同的是，
// arePropsEqual 返回 true 时，不会触发 render，如果返回 false，则会。
// 而 shouldComponentUpdate 刚好与其相反。
export default connect(() => ({}), mapDispatchToProps)(React.memo(FrontendAuth, arePropsEqual))